package online.longzipeng.cinemasys.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import online.longzipeng.cinemasys.common.annotion.NeedPermissions;
import online.longzipeng.cinemasys.common.exception.AppException;
import online.longzipeng.cinemasys.common.result.ResponseEnum;
import online.longzipeng.cinemasys.common.result.Result;
import online.longzipeng.cinemasys.entity.Resources;
import online.longzipeng.cinemasys.service.ResourcesService;
import online.longzipeng.cinemasys.vo.resources.ResourcesSaveVO;
import online.longzipeng.cinemasys.vo.resources.ResourcesUpdateVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lzp
 * @since 2021-04-08
 */
@RestController
@RequestMapping("/resources")
@Api(value = "资源相关接口",description = "资源相关接口",tags = "资源相关接口")
public class ResourcesController {

    @Autowired
    ResourcesService resourcesService;

    @PostMapping("/save")
    @NeedPermissions("resources:save")
    @ApiOperation("新增资源")
    public Result save(@Valid @RequestBody ResourcesSaveVO resourcesSaveVO){
        Resources resources = new Resources();
        BeanUtils.copyProperties(resourcesSaveVO,resources);
        resourcesService.add(resources);
        return Result.success(null,"资源添加成功！！");
    }

    @GetMapping("/delete-one")
    @NeedPermissions("resources:delete")
    @ApiOperation("删除资源")
    public Result deleteOne(@ApiParam(value = "资源id",required = true)Long id){
        try {
            resourcesService.removeById(id);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppException(ResponseEnum.FAILED);
        }
        return Result.success(null,"资源删除成功！！");
    }

    @GetMapping("/delete")
    @NeedPermissions("resources:delete")
    @ApiOperation("删除多个资源")
    public Result deleteOne(@ApiParam(value = "资源id数组",required = true)Long[] ids){
        List<Long> idList = Arrays.stream(ids).collect(Collectors.toList());
        try {
            resourcesService.removeByIds(idList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppException(ResponseEnum.FAILED);
        }
        return Result.success(null,"资源删除成功！！");
    }

    @PostMapping("/update")
    @NeedPermissions("resources:update")
    @ApiOperation("修改资源")
    public Result update(@Valid @RequestBody ResourcesUpdateVO resourcesUpdateVO) {
        Resources resources = new Resources();
        BeanUtils.copyProperties(resources,resources);
        resourcesService.updateReSources(resources);
        return Result.success("资源修改成功！！");
    }
}
